/**
 * Filename: PushYNReceiver.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/16 16:55
 */
package com.github.postsanf.yinian.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.CardStatusDetailActivity;
import com.github.postsanf.yinian.activity.EveryDayNoticeDialogActivity;
import com.github.postsanf.yinian.activity.MainActivity;
import com.github.postsanf.yinian.activity.NewsActivity;
import com.github.postsanf.yinian.activity.TimeGoodsWebActivity;
import com.github.postsanf.yinian.activity.TodayShowActivity;
import com.github.postsanf.yinian.bean.YNNewStaus;
import com.github.postsanf.yinian.bean.YNNewsComment;
import com.github.postsanf.yinian.bean.YNNewsNotice;
import com.github.postsanf.yinian.bean.YNStatus;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.entity.YNDayNoticeResponse;
import com.github.postsanf.yinian.entity.YNNewsCommentResponse;
import com.github.postsanf.yinian.entity.YNNewsInviteResponse;
import com.github.postsanf.yinian.entity.YNNewsNoticeResponse;
import com.github.postsanf.yinian.entity.YNStatusResponse;
import com.github.postsanf.yinian.entity.YNTodayResponse;
import com.github.postsanf.yinian.utils.NotificationUtil;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.SystemUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.LinkedHashMap;

import easeui.utils.TextBase64Util;

/**
 * 个推接受
 */
public class PushYNReceiver extends BroadcastReceiver {
    private Gson gson = new Gson();
    NotificationUtil notice = null;
    Intent intent;
    int smallIcon = R.drawable.ic_add_white_24dp;
    String ticker = "来了条新的通知";
    int LargeIcon = R.drawable.ic_launcher;

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("xjs", "onReceiveonReceive");
        Bundle bundle = intent.getExtras();
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                Log.i("xjs", "bundle.tossssssss===>" + bundle.toString());
                byte[] payload = bundle.getByteArray("payload");
                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");
                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
                // System.out.println("第三方回执接口调用" + (result ? "成功" : "失败"));
                // 解析数据
                if (payload != null) {
                    String data = new String(payload);
                    Log.i("xjs", "datadatadata===>" + data.toString());
                    int code = -1;
                    try {
                        JSONTokener jsonParser = new JSONTokener(data);
                        JSONObject res = (JSONObject) jsonParser.nextValue();
                        code = res.getInt("code");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (notice == null) {
                        notice = new NotificationUtil(context, code);
                    }
                    SharedPreferences sharedPreferences = context
                            .getSharedPreferences(ACTIONs.mymsg, 0);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    switch (code) {
                        case 0:
                            // 邀请数据
                            YNNewsInviteResponse resInvite = gson.fromJson(data, YNNewsInviteResponse.class);
                            if (resInvite != null) {
                                editor.putBoolean(ACTIONs.invitebb, true);
                                int invitenum = sharedPreferences.getInt(ACTIONs.invitenum, 0);
                                invitenum++;
                                editor.putInt(ACTIONs.invitenum, invitenum);
                                editor.commit();
                                Intent iIntent = new Intent(ACTIONs.actionDoInvate);
                                iIntent.putExtra(ACTIONs.aInvateDatas, resInvite.getData().get(0));
                                context.sendBroadcast(iIntent);
                                // 更新标记
//                                ((BaseApplication)context.getApplicationContext()).getYnCount().setAddInvate();
//                                Intent redIntent = new Intent(ACTIONs.actionUpdateRed);
//                                context.sendBroadcast(redIntent);
                                // 更新通知
                                notice.normal_notification(new Intent(context, NewsActivity.class), smallIcon, ticker, resInvite.getData().get(0).getUnickname(),
                                        resInvite.getData().get(0).getIgcontent());
                            }
                            break;
                        case 1:
                            // 发表评论
                            YNNewsCommentResponse resComment = gson.fromJson(data, YNNewsCommentResponse.class);
                            if (resComment != null) {
                                editor.putBoolean(ACTIONs.commentbb, true);
                                int commentnum = sharedPreferences.getInt(ACTIONs.commentnum, 0);
                                commentnum++;
                                editor.putInt(ACTIONs.commentnum, commentnum);
                                editor.commit();
                                Intent cIntent = new Intent(ACTIONs.actionDoNews);
                                cIntent.putExtra(ACTIONs.aNewsDatas, resComment.getData().get(0));
                                context.sendBroadcast(cIntent);
                                // 更新标记
//                                ((BaseApplication)context.getApplicationContext()).getYnCount().setAddComment();
//                                Intent redIntent = new Intent(ACTIONs.actionUpdateRed);
//                                context.sendBroadcast(redIntent);
                                // 更新通知
                                viewSingleStatus(context, resComment.getData().get(0));
                            }
                            break;
                        case 2:
                            // 删除组、成员进组
                            YNNewsNoticeResponse resNotice = gson.fromJson(data, YNNewsNoticeResponse.class);
                            if (resNotice != null) {
                                editor.putBoolean(ACTIONs.notifybb, true);
                                int notifynum = sharedPreferences.getInt(ACTIONs.notifynum, 0);
                                notifynum++;
                                editor.putInt(ACTIONs.notifynum, notifynum);
                                editor.commit();
                                Intent nIntent = new Intent(ACTIONs.actionDoNotice);
                                nIntent.putExtra(ACTIONs.aNoticeDatas, resNotice.getData().get(0));
                                context.sendBroadcast(nIntent);
                                YNNewsNotice ynNewsNotice = resNotice.getData().get(0);
                                if (ynNewsNotice.getNcontent().contains("加入")) {
                                    Intent intent1 = new Intent(ACTIONs.AddMember);
                                    context.sendBroadcast(intent1);
//                                    sendJoinHuanXinGroup(ynNewsNotice.getGimid(), ynNewsNotice.getUnickname());
                                }
                                if (ynNewsNotice.getNcontent().contains("退出")) {
                                    Intent intent1 = new Intent(ACTIONs.deleteMember);
                                    context.sendBroadcast(intent1);
                                }
                                // 更新标记
//                                ((BaseApplication)context.getApplicationContext()).getYnCount().setAddNotification();
//                                Intent redIntent = new Intent(ACTIONs.actionUpdateRed);
//                                context.sendBroadcast(redIntent);
                                // 更新通知
                                context.sendBroadcast(new Intent(ACTIONs.actionAlbumInit));
                                notice.normal_notification(new Intent(context, MainActivity.class), smallIcon, ticker, resNotice.getData().get(0).getUnickname(),
                                        resNotice.getData().get(0).getNcontent());
                            }
                            break;
                        case 3:
                            // 新动态
                            YNNewStaus resStatus = gson.fromJson(data, YNNewStaus.class);
                            if (resStatus != null) {
//                                Intent sIntent = new Intent(ACTIONs.actionDoStatus);
//                                sIntent.putExtra(ACTIONs.aStatusDatas, resStatus.getData()[0].getGroupid());
//                                context.sendBroadcast(sIntent);
                                Intent broadcastIntent = new Intent(context, NoticeBroadcast.class);
                                broadcastIntent.putExtra("groupid", resStatus.getData().get(0).getGroupid());
                                PendingIntent pendingIntent = PendingIntent.
                                        getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                                NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                                builder.setContentTitle("新动态")
                                        .setContentText(resStatus.getData().get(0).getPushContent())
                                        .setTicker(ticker)
                                        .setContentIntent(pendingIntent)
                                        .setSmallIcon(smallIcon)
                                        .setAutoCancel(true)
                                        .setPriority(NotificationCompat.PRIORITY_MAX)
                                        .setDefaults(Notification.DEFAULT_ALL);
                                NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                                manager.notify(2, builder.build());
//                                notice.normal_notification(intent1, smallIcon, ticker, "新动态", resStatus.getData().get(0).getPushContent());
                            }
                            break;
                        case 4:
                            YNTodayResponse resToday = gson.fromJson(data, YNTodayResponse.class);
                            if (resToday != null) {
                                String text = resToday.getData().get(0).getContent();
                                if (text.contains("#")) {
                                    if (text.substring(text.indexOf("#"), text.lastIndexOf("#")).equals("印品商城")) {
                                        notice.normal_notification(new Intent(context, TimeGoodsWebActivity.class), smallIcon, ticker, "印品商城",
                                                text);
                                    } else if (text.substring(text.indexOf("#"), text.lastIndexOf("#")).equals("今日忆")) {
                                        Intent nIntent = new Intent(ACTIONs.actionDoPopToday);
                                        context.sendBroadcast(nIntent);
                                        notice.normal_notification(new Intent(context, TodayShowActivity.class), smallIcon, ticker, "今日忆",
                                                text);
                                    } else {
                                        notice.normal_notification(new Intent(context, MainActivity.class), smallIcon, ticker, "忆年",
                                                text);
                                    }
                                } else {
                                    notice.normal_notification(new Intent(context, MainActivity.class), smallIcon, ticker, "忆年",
                                            text);
                                }
                            }
                            break;
                        case 5:
                            YNDayNoticeResponse resDayNotice = gson.fromJson(data, YNDayNoticeResponse.class);
                            if (resDayNotice != null) {
                                String title = resDayNotice.getData().get(0).getTitle();
                                String content = resDayNotice.getData().get(0).getContent();
                                context.sendBroadcast(new Intent(ACTIONs.actionDoPopEveryDayNotice));
                                Intent[] intents = new Intent[2];
                                intents[0] = Intent.makeRestartActivityTask(new ComponentName(context, MainActivity.class));
                                intents[1] = new Intent(context, EveryDayNoticeDialogActivity.class);
                                notice.normal_notification(intents, smallIcon, ticker, title,
                                        content);
//                                notice.normal_notification(new Intent(context, EveryDayNoticeDialogActivity.class), smallIcon, ticker, title,
//                                        content);
                            }
                            break;
                    }
                }
                context.sendBroadcast(new Intent(ACTIONs.actionMymessageNums));
                //判断app进程是否存活
                if (!SystemUtils.isAppAlive(context, "com.github.postsanf.yinian")) {
                    Log.i("xjs", "launchIntent==>");
                    Intent launchIntent = context.getPackageManager().
                            getLaunchIntentForPackage("com.github.postsanf.yinian");
                    launchIntent.setFlags(
                            Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                    context.startActivity(launchIntent);
                }
                break;
            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                Log.i("xjs","cid==>"+cid);
                break;
            case PushConsts.THIRDPART_FEEDBACK:
                break;
            default:
                break;
        }
    }

    private void sendJoinHuanXinGroup(String gimid, String unickname) {
        EMMessage message = EMMessage.createTxtSendMessage(TextBase64Util.encode("加入"), gimid);
        if (message == null) {
            return;
        }
        Log.i("xjs", "sendjoinHuanXinGroup==>" + gimid);
        message.setChatType(EMMessage.ChatType.GroupChat);
        message.setAttribute("type", String.valueOf(66));
        message.setAttribute("intoQuitMessage", unickname + "加入了本圈子");
        EMClient.getInstance().chatManager().sendMessage(message);
    }

    public void viewSingleStatus(final Context context, final YNNewsComment ynnewscomment) {
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        mParam.put(CommonConstants.YNS_EVENT_ID, String.valueOf(ynnewscomment.getMeid()));
        StringRequest req = new StringRequest(context.getString(R.string.BASE_URL) + context.getString(R.string.ynShowSingleEvent))
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNStatusResponse resSingleStatus = gson.fromJson(s, YNStatusResponse.class);
//                        Log.i("xjs","viewSingleStatus===ss==>"+s);
                        if (resSingleStatus != null && ReqUtils.isSuccess(resSingleStatus.getCode())) {
                            YNStatus status = resSingleStatus.getData().get(0);
                            if (status == null) {
                                return;
                            }
                            YNSingleton.getInstance().setCurStatus(status);
                            Intent intent = new Intent(context, CardStatusDetailActivity.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                            notice.normal_notification(intent, smallIcon, ticker, ynnewscomment.getUnickname(),
                                    ynnewscomment.getMcontent());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                    }
                });
        LiteHttp.newApacheHttpClient(new HttpConfig(context)).executeAsync(req);
    }

}
